<template>
  <div class="container">
    <div class="upload">
      <!-- {{ fileList }} -->
      <div>
        <el-upload
          action=""
          ref="uploadVideo"
          :file-list="fileList"
          :on-change="fileChange"
          accept=".mp4"
          :limit="1"
          :auto-upload="false"
          style="display: inline-block"
        >
          <el-tooltip
            content="只能上传mp4格式的视频"
            placement="top"
            effect="light"
          >
            <el-button type="primary" size="small">选择视频</el-button>
          </el-tooltip>
          <!-- <div slot="tip" class="el-upload__tip">只能上传mp4文件</div> -->
        </el-upload>

        <label class="status"
          >上传状态: <span>{{ statusText }}</span></label
        >
      </div>
      <div>
        <el-button
          size="mini"
          type="success"
          @click="authUpload"
          :disabled="uploadDisabled"
          >上传</el-button
        >
        <el-button
          size="mini"
          type="info"
          @click="pauseUpload"
          :disabled="pauseDisabled"
          >暂停</el-button
        >
        <el-button
          size="mini"
          type="warning"
          :disabled="resumeDisabled"
          @click="resumeUpload"
        >
          恢复
        </el-button>
        <el-progress :percentage="authProgress"></el-progress>
      </div>
    </div>
  </div>
</template>
<script>
import axios from "axios";
import "@/utils/aliyun-upload-sdk/aliyun-upload-sdk-1.5.4.min.js";
// import "@/utils/aliyun-upload-sdk/lib/es6-promise.min.js";
import "@/utils/aliyun-upload-sdk/lib/aliyun-oss-sdk-6.17.1.min.js";

export default {
  props: ["fileList"],
  data() {
    return {
      timeout: "",
      partSize: "",
      parallel: "",
      retryCount: "",
      retryDuration: "",
      region: "cn-shanghai",
      userId: "241474229795852336",
      file: null,
      uploadDisabled: true,
      resumeDisabled: true,
      pauseDisabled: true,
      uploader: null,
      authProgress: 0,
      statusText: "",
      fileSize: 0,
      baseUrl: process.env.BASE_API,
    };
  },
  methods: {
    fileChange(file, fileList) {
      if (this.$refs["uploadVideo"] !== undefined) {
        this.$refs["uploadVideo"].clearFiles();
      }
      this.file = file.raw;
      this.fileSize = file.size;
      if (!this.file) {
        alert("请先选择需要上传的文件!");
        return;
      }
      var Title = this.file.name;
      var userData = '{"Vod":{ "Title": "' + Title + '"}}';
      if (this.uploader) {
        this.uploader.stopUpload();
        this.authProgress = 0;
        this.statusText = "";
      }
      this.uploader = this.createUploader();
      // console.log(userData);
      this.uploader.addFile(this.file, null, null, null, userData);
      this.uploadDisabled = false;
      this.pauseDisabled = true;
      this.resumeDisabled = true;
    },
    authUpload() {
      // 然后调用 startUpload 方法, 开始上传
      if (this.uploader !== null) {
        this.uploader.startUpload();
        this.uploadDisabled = true;
        this.pauseDisabled = false;
      }
    },
    // 暂停上传
    pauseUpload() {
      if (this.uploader !== null) {
        this.uploader.stopUpload();
        this.resumeDisabled = false;
        this.pauseDisabled = true;
      }
    },
    // 恢复上传
    resumeUpload() {
      if (this.uploader !== null) {
        this.uploader.startUpload();
        this.resumeDisabled = true;
        this.pauseDisabled = false;
      }
    },
    createUploader(type) {
      let self = this;
      let uploader = new AliyunUpload.Vod({
        timeout: self.timeout || 600000,
        partSize: Math.round(self.partSize || 1048576),
        parallel: self.parallel || 5,
        retryCount: self.retryCount || 3,
        retryDuration: self.retryDuration || 2,
        // region: "cn-beijing",
        userId: self.userId,
        // 添加文件成功
        addFileSuccess: function (uploadInfo) {
          self.uploadDisabled = false;
          self.resumeDisabled = false;
          self.statusText = "添加文件成功, 等待上传...";
          self.$emit("pre-upload");
          // console.log("addFileSuccess: " + uploadInfo.file.name);
        },
        // 开始上传
        onUploadstarted: function (uploadInfo) {
          // 如果是 UploadAuth 上传方式, 需要调用 uploader.setUploadAuthAndAddress 方法
          // 如果是 UploadAuth 上传方式, 需要根据 uploadInfo.videoId是否有值，调用点播的不同接口获取uploadauth和uploadAddress
          // 如果 uploadInfo.videoId 有值，调用刷新视频上传凭证接口，否则调用创建视频上传凭证接口
          // 注意: 这里是测试 demo 所以直接调用了获取 UploadAuth 的测试接口, 用户在使用时需要判断 uploadInfo.videoId 存在与否从而调用 openApi
          // 如果 uploadInfo.videoId 存在, 调用 刷新视频上传凭证接口(https://help.aliyun.com/document_detail/55408.html)
          // 如果 uploadInfo.videoId 不存在,调用 获取视频上传地址和凭证接口(https://help.aliyun.com/document_detail/55407.html)
          if (!uploadInfo.videoId) {
            let createUrl =
              self.baseUrl +
              "/vod/getUploadAuthAndAddress/" +
              self.file.name +
              "/" +
              self.file.name;
            axios.get(createUrl).then((res) => {
              let data = res.data.data;
              let uploadAuth = data.uploadAuth;
              let uploadAddress = data.uploadAddress;
              let videoId = data.videoId;
              uploader.setUploadAuthAndAddress(
                uploadInfo,
                uploadAuth,
                uploadAddress,
                videoId
              );
            });
            self.statusText = "文件开始上传...";
            // console.log(
            //   "onUploadStarted:" +
            //     uploadInfo.file.name +
            //     ", endpoint:" +
            //     uploadInfo.endpoint +
            //     ", bucket:" +
            //     uploadInfo.bucket +
            //     ", object:" +
            //     uploadInfo.object
            // );
          } else {
            // 如果videoId有值，根据videoId刷新上传凭证
            // https://help.aliyun.com/document_detail/55408.html?spm=a2c4g.11186623.6.630.BoYYcY
            let refreshUrl =
              self.baseUrl + "/vod/refreshUploadAuth/" + uploadInfo.videoId;
            axios.get(refreshUrl).then((res) => {
              let data = res.data.data;
              let uploadAuth = data.uploadAuth;
              let uploadAddress = data.uploadAddress;
              let videoId = data.videoId;
              uploader.setUploadAuthAndAddress(
                uploadInfo,
                uploadAuth,
                uploadAddress,
                videoId
              );
            });
          }
        },
        // 文件上传成功
        onUploadSucceed: function (uploadInfo) {
          // console.log(
          //   "onUploadSucceed: " +
          //     uploadInfo.file.name +
          //     ", endpoint:" +
          //     uploadInfo.endpoint +
          //     ", bucket:" +
          //     uploadInfo.bucket +
          //     ", object:" +
          //     uploadInfo.object
          // );
          self.statusText = "文件上传成功!";
          self.$message.success("文件上传成功!");
          // 上传成功后，返回给父组件对应的视频id 和 文件大小
          let res = {
            videoId: uploadInfo.videoId,
            fileSize: self.fileSize / 1024 / 1024,
            fileName: self.file.name,
            success: true,
          };
          self.$emit("upload-success", res);
        },
        // 文件上传失败
        onUploadFailed: function (uploadInfo, code, message) {
          // console.log(
          //   "onUploadFailed: file:" +
          //     uploadInfo.file.name +
          //     ",code:" +
          //     code +
          //     ", message:" +
          //     message
          // );
          self.statusText = "文件上传出错!请点击恢复";
        },
        // 取消文件上传
        onUploadCanceled: function (uploadInfo, code, message) {
          // console.log(
          //   "Canceled file: " +
          //     uploadInfo.file.name +
          //     ", code: " +
          //     code +
          //     ", message:" +
          //     message
          // );
          self.statusText = "文件已暂停上传";
        },
        // 文件上传进度，单位：字节, 可以在这个函数中拿到上传进度并显示在页面上
        onUploadProgress: function (uploadInfo, totalSize, progress) {
          // console.log(
          //   "onUploadProgress:file:" +
          //     uploadInfo.file.name +
          //     ", fileSize:" +
          //     totalSize +
          //     ", percent:" +
          //     Math.ceil(progress * 100) +
          //     "%"
          // );
          let progressPercent = Math.ceil(progress * 100);
          self.authProgress = progressPercent;
          self.statusText = "文件上传中...";
        },
        // 上传凭证超时
        onUploadTokenExpired: function (uploadInfo) {
          // 上传大文件超时, 如果是上传方式一即根据 UploadAuth 上传时
          // 需要根据 uploadInfo.videoId 调用刷新视频上传凭证接口(https://help.aliyun.com/document_detail/55408.html)重新获取 UploadAuth
          // 然后调用 resumeUploadWithAuth 方法, 这里是测试接口, 所以我直接获取了 UploadAuth
          let refreshUrl =
            self.baseUrl + "/vod/refreshUploadAuth/" + uploadInfo.videoId;
          axios.get(refreshUrl).then((res) => {
            let data = res.data.data;
            let uploadAuth = data.uploadAuth;
            uploader.resumeUploadWithAuth(uploadAuth);
            console.log(
              "upload expired and resume upload with uploadauth " + uploadAuth
            );
          });
          self.statusText = "文件超时...";
          self.$message.warning("文件超时...");
        },
        // 全部文件上传结束
        onUploadEnd: function (uploadInfo) {
          // console.log("onUploadEnd: uploaded all the files");
          self.statusText = "文件上传完毕";
        },
      });
      return uploader;
    },
  },
};
</script>
<style>
/* .upload-type-switch {
  text-align: center;
}
.container {
  width: 1200px;
  margin: 0 auto;
}
.input-control {
  margin: 5px 0;
}
.input-control label {
  font-size: 14px;
  color: #333;
  width: 30%;
  text-align: right;
  display: inline-block;
  vertical-align: middle;
  margin-right: 10px;
}
.input-control input {
  width: 30%;
  height: 30px;
  padding: 0 5px;
}
.upload {
  padding: 30px 50px;
}
.upload-type {
  color: #666;
  font-size: 12px;
  padding: 10px 0;
}
.upload-type button {
  margin: 0 10px 0 20px;
}
.progress {
  font-size: 14px;
  color: blue;
}
.progress i {
  font-style: normal;
}
.info {
  font-size: 14px;
  padding-left: 30px;
} */

.status {
  font-size: 14px;
  margin-left: 30px;
}
</style>